package core;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

public abstract class UnitAbstract implements Unit {

	private transient List<UnitConnection> obserwers = new ArrayList<UnitConnection>();
	protected String[] inputs = new String[0];
	protected String[] outputs = new String[0];
	
	protected void sendData(DataPackage dataPack, String sPort){
		synchronized(obserwers){
			for(UnitConnection ui : obserwers){
				if(this.getOutputsCount()==1 || ui.getSPort().equals(sPort)){
					ui.getTarget().read(dataPack.clone(), ui.getTPort());
				}
			}
		}
	}
	protected void sendData(DataPackage dataPack){
		sendData(dataPack,outputs[0]);
	}
	public void connect(UnitConnection ui){
		synchronized(obserwers){
			obserwers.add(ui);
		}
	}
	public void disconnect(UnitConnection rem){
		synchronized(obserwers){
			obserwers.remove(rem);
		}
	}
	private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
		in.defaultReadObject();
		obserwers = new ArrayList<UnitConnection>();
	}
	@Override
	public int getInputsCount() {
		return inputs.length;
	}
	public int getOutputsCount() {
		return outputs.length;
	}
	public String getInput(int i){
		return inputs[i];
	}
	public String getOutput(int i){
		return outputs[i];
	}
}
